package controller

import (

	"ginEssential/model"
	"ginEssential/repository"
	"ginEssential/response"
	"ginEssential/vo"
	"github.com/gin-gonic/gin"

)

type ICategoryController interface {
	RestController
}
type CategoryController struct {
	Repository repository.CategoryRepository
}

func NewCategoryController() ICategoryController {
	repository:=repository.NewCategoryRepository()
	repository.DB.AutoMigrate(&model.Category{})
	return &CategoryController{Repository:repository}
}

func (c2 *CategoryController) Create(c *gin.Context) {
	var requestCategory vo.CreateCategoryRequest
	if err:=c.BindJSON(&requestCategory);err!=nil{
		response.Failed(c,nil,"验证错误 字段不能为空")
		return
	}
	var category *model.Category
	var err error
	if category,err=c2.Repository.Create(requestCategory.Name);err!=nil{
		panic(err)
		return
	}
	response.Success(c,gin.H{"category": category},"分类成功")
}

func (c2 *CategoryController) Update(c *gin.Context) {

	//绑定body中的参数
	var requestCategory model.Category
	c.BindJSON(&requestCategory)
	if requestCategory.Name==""{
		response.Failed(c,nil,"数据验证错误 分类名称必填")
		return
	}
	//获取path中的参数
	categoryid:=c.Param("id")
	//数据库查找
	var updateCatefory model.Category
	if c2.Repository.DB.Where("id=?",categoryid).First(&updateCatefory).RecordNotFound(){
		 response.Failed(c,nil,"分类不存在")
		return
	}
	//更新分类
	category,err:=c2.Repository.Update(updateCatefory,updateCatefory.Name)
	if err!=nil{
		response.Failed(c,nil,"更新出错")
		return
	}
	response.Success(c,gin.H{"category":category},"修改成功")
}

func (c2 *CategoryController) Show(c *gin.Context) {
	//获取path中的参数
	categoryid:=c.Param("id")
	category,err:=c2.Repository.SelectById(categoryid)
	if err!=nil {
		response.Failed(c,nil,"分类不存在")
		return
	}
	response.Success(c,gin.H{"category":category},"查找成功")
}

func (c2 *CategoryController) Delete(c *gin.Context) {
	//获取path中的参数
	categoryid:=c.Param( "id")
	err:=c2.Repository.DeleteById(categoryid)
	if err!=nil{
		response.Failed(c,nil,"删除失败")
	}
	response.Success(c,nil,"删除成功")
}
